import json

from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from fdfs_client.client import Fdfs_client

from .models import Area, House, Facility, HouseImage


class AreaView(View):
    def get(self, request):
        """获取所有地域信息"""

        areas = Area.objects.all()
        area_data = []
        for area in areas:
            area_data.append({
                'aid': area.id,
                'aname': area.name
            })
        res = {
            'errno': 0,
            'errmsg': '获取成功',
            'data': area_data
        }
        return JsonResponse(res)


class HouseView(LoginRequiredMixin, View):
    def post(self, request):
        """新建房源信息"""

        # 获取数据
        user = request.user
        house_data = json.loads(request.body)
        title = house_data.get('title')
        price = house_data.get('price')
        area_id = house_data.get('area_id')
        address = house_data.get('address')
        room_count = house_data.get('room_count')
        acreage = house_data.get('acreage')
        unit = house_data.get('unit')
        capacity = house_data.get('capacity')
        beds = house_data.get('beds')
        deposit = house_data.get('deposit')
        min_days = house_data.get('min_days')
        max_days = house_data.get('max_days')
        facility = house_data.get('facility')

        # 校验数据
        # if not all([title, price, area_id, address, room_count, acreage, unit, capacity, beds, deposit, min_days, max_days, facility]):
        #     return JsonResponse({'errno': 0, 'errmsg': '参数不全'})

        # 业务处理
        house = House.objects.create(
            title=title,
            price=price,
            area_id=1,
            address=address,
            room_count=room_count,
            acreage=acreage,
            unit=unit,
            capacity=capacity,
            beds=beds,
            deposit=deposit,
            min_days=min_days,
            max_days=max_days,
            user=user
        )
        house.facility = Facility.objects.filter(id__in=facility)
        house.save()

        # 返回响应
        res = {
            'errno': 0,
            'errmsg': '发布成功',
            'data': {
                'house_id': house.id
            }
        }
        return JsonResponse(res)


class ShowAddHouseView(View):
    def get(self, request):
        return render(request, 'newhouse.html')


class AddHouseImageView(LoginRequiredMixin, View):
    def post(self, request, house_id):
        """上传房源图片"""
        # 获取数据
        image = request.FILES.get('house_image')

        # 校验数据
        if not image:
            return JsonResponse({'errno': 4101, 'errmsg': '请选择图前`图片'})

        client = Fdfs_client(settings.CONFIG_URL)
        image_buffer = image.read()
        ret = client.upload_by_buffer(image_buffer)

        if ret['Status'] != 'Upload successed.':
            return JsonResponse({'errno': 4101, 'errmsg': '图片上传失败'})

        image_url = ret['Remote file_id']
        House.objects.filter(id=house_id).update(index_image_url=image_url)
        HouseImage.objects.create(house_id=house_id, url=image_url)

        res = {
            'errno': 0,
            'errmsg': '图片上传成功',
            'data': {
                'url': settings.BASE_URL + image_url
            }
        }


class UserHousesView(View):
    def get(self, request):
        """获取我发布的房源信息"""

        user = request.user

        if not user.is_authenticated:
            return JsonResponse({'errno': 4101, 'errmsg': '用户未登录'})

        houses = user.houses

        house_list = []
        for house in houses:
            house_data = {
                'address': house.address,
                'area_name': house.area.name,
                'ctime': house.create_time,
                'house_id': house.id,
                'img_url': house.index_image_url,
                'order_count': house.order_count,
                'price': house.price,
                'room_count': house.room_count,
                'title': house.title,
                'use_avatar': user.avatar.url
            }
            house_list.append(house_data)

        res = {
            'errno': 0,
            'errmsg': 'ok',
            'data': {
                'houses': house_list
            }
        }
        return JsonResponse(res)


class ShowHousesView(View):
    def get(self, request):
        """首页推荐房源"""

        houses = House.objects.order_by('-id')[0: 4]
        house_list = []
        for house in houses:
            house_data = {
                'house_id': house.id,
                'img_url': settings.BASE_URL + house.index_image_url,
                'title': house.title
            }
            house_list.append(house_data)

        res = {
            'data': house_list,
            'errmsg': 'OK',
            'errno': '0'
        }
        return JsonResponse(res)


class SearchHousesView(View):
    def get(self, request):
        """房源搜索"""

        # 接受数据
        recv_data = json.loads(request.body)
        area_id = recv_data.get('aid')
        start_date = recv_data.get('sd')
        end_date = recv_data.get('ed')
        sort_key = recv_data.get('sk')
        page = recv_data.get('p')

        if not all([area_id, start_date, end_date, sort_key, page]):
            return JsonResponse({'errno': '9999', 'errmsg': '参数不全'}, status=400)

        import datetime
        start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d').date()
        end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d').date()
        daysdelta = (end_date - start_date).days

        from django.db.models import Q
        houses_all = House.objects.order_by(sort_key).filter(Q(area_id=area_id)&(Q(max_days=0)|Q(max_days__gte=daysdelta))&Q(min_days=daysdelta))

        from math import ceil
        count = houses_all.count()
        total_page = ceil(count / 5)

        houses = houses_all[(page -1) * 5: page * 5]

        house_list = []
        for house in houses:
            house_dict = {
                "address": house.address,
                "area_name": house.area.name,
                "ctime": house.create_time.date(),
                "house_id": house.id,
                "img_url": house.index_image_url,
                "order_count": house.order_count,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                "user_avatar": house.user.avatar.url
            }
            house_list.append(house_dict)

        res = {
            'data': {
                'houses': house_list,
                'total_page': total_page
            },
            'errno': 0,
            'errmsg': '请求成功'
        }
        return JsonResponse(res, status=200)


class HouseDetailView(View):
    def get(self, request, house_id):
        """获取房源详情"""
        try:
            house = House.objects.get(id=house_id)
        except:
            return JsonResponse({
                'errno': 9999,
                'errmsg': '找不到房源'
            })

        user = request.user
        if user.is_authenticated:
            user_id = user.id
        else:
            user_id = -1

        facilities = house.facility.all()
        facilites_list = []
        for facility in facilities:
            facilites_list.append(facility.id)

        images = HouseImage.objects.filter(house=house)
        img_urls = []
        for image in images:
            img_urls.append(image.url)

        orders = house.order_set.all()
        comments = []
        for order in orders:
            comments.append({
                "comment": order.comment,
                "ctime": order.update_time.date(),
                "user_name": order.user.name
            })

        house_data = {
            'acreage': house.acreage,
            'address': house.address,
            'beds': house.beds,
            'capacity': house.capacity,
            'deposit': house.deposit,
            'hid': house.id,
            'max_days': house.max_days,
            'min_days': house.min_days,
            'price': house.price,
            'room_count': house.room_count,
            'title': house.title,
            'unit': house.unit,
            'user_avatar': house.user.avatar.url,
            'user_id': house.user.id,
            'user_name': house.user.username,
            'facilities': facilites_list,
            'img_urls': img_urls,
            'comments': comments
        }

        res = {
            'data': {
                'house': house_data,
                'user_id': user_id
            },
            'errmsg': 'OK',
            'errno': 0
        }
        return JsonResponse(res)